package com.jxb.currentLimiting;

/**
 * 令牌桶算法
 */
public class TokenBucket {

    public static long timeStamp = System.currentTimeMillis();//当前时间
    public static long capacity = 100;//桶的容量
    public static long rate = 1;//令牌放入桶的速度
    public static long tokens = 10;//当前令牌的数量

    public static void main(String[] args) {
        while (true) {
            if (!grant()) {
                System.out.println("tokens:-------->"+tokens);
                System.out.println("被限流了");
            }
        }
    }

    public static boolean grant() {
        long now = System.currentTimeMillis();
        //添加令牌-每秒钟添加rate个令牌
        tokens = Math.min(capacity,tokens + (now -timeStamp)/1000 * rate);
        timeStamp = now;
        if (tokens < 1) {
            //若不到一个令牌，则拒绝
            return false;
        }else {
            //还有令牌，领取令牌
            tokens -= 1;
            return true;
        }
    }



}
